# code:utf8
import json
import logging
import math
from datetime import datetime
from pyquery import PyQuery
from zc_core.model.items import *
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_number, parse_timestamp
from zc_core.util.encrypt_util import build_sha1_order_id, md5
from zc_core.util.order_deadline_filter import OrderItemFilter
from zc_core.util.sku_id_parser import convert_id2code

from ctaxccgp.items import BackBrand, BackSpu, BackCatAttr
from ctaxccgp.matcher import match_supplier_id

logger = logging.getLogger('rule')
order_filter = OrderItemFilter()


# 解析area列表
def parse_area(response):
    rows = json.loads(response.text).get('result', [])
    areas = list()
    for row in rows:
        area = _build_area(row)
        areas.append(area)

    return areas


def _build_area(row):
    area = Area()
    area['areaId'] = str(row.get('id'))
    area['areaName'] = row.get('name')
    area['areaCode'] = row.get('pinyin')
    area['parentId'] = str(row.get('pid'))
    area['level'] = row.get('level')

    return area


# 解析店铺catalog列表
def parse_back_catalog(response):
    rows = json.loads(response.text)
    cats = list()
    for lv1 in rows:
        cat1 = _build_back_catalog(lv1)
        cats.append(cat1)

        for lv2 in lv1.get('children', []):
            cat2 = _build_back_catalog(lv2)
            cats.append(cat2)

            for lv3 in lv2.get('children', []):
                cat3 = _build_back_catalog(lv3)
                cats.append(cat3)

    return cats


def _build_back_catalog(row):
    cat = Catalog()
    node = row.get('node', {})
    cat['catalogId'] = str(node.get('id'))
    cat['catalogName'] = node.get('name')
    cat['parentId'] = str(node.get('pid'))
    cat['level'] = node.get('level')
    if cat['level'] == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


def parse_supplier(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    rs = json.loads(response.text)
    rows = rs.get('result', {}).get('data', [])
    sp_list = list()
    for row in rows:
        supplier = Supplier()
        supplier['id'] = row.get('shopId')
        supplier['name'] = row.get('nameHover')
        supplier['batchNo'] = batch_no
        sp_list.append(supplier)

    return sp_list


def parse_cat_brand(response):
    rs_list = list()
    meta = response.meta
    batch_no = meta.get('batchNo')
    cat_id = meta.get('catalogId')
    cat_name = meta.get('catalogName')
    rs = json.loads(response.text)
    if rs and rs.get('result', None):
        for row in rs.get('result', []):
            brand_id = row.get('brandId')
            br = BackBrand()
            br['id'] = '{}_{}'.format(cat_id, brand_id)
            br['code'] = brand_id
            br['name'] = row.get('brandName')
            br['catId'] = cat_id
            br['catName'] = cat_name
            br['batchNo'] = batch_no
            rs_list.append(br)

    return rs_list


def parse_sku_page(response, page_size):
    rs = json.loads(response.text)
    entities = rs.get('result', {}).get('searchWithAggs', {}).get('entities', {})
    if entities and not entities.get('empty'):
        total = entities.get('total')
        if total:
            return math.ceil(int(total) / page_size)

    return 0


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    sp_id = meta.get('supplierId')
    sp_name = meta.get('supplierName')
    batch_no = meta.get('batchNo')

    rs = json.loads(response.text)
    entities = rs.get('result', {}).get('searchWithAggs', {}).get('entities', {})
    sku_list = list()
    if entities and not entities.get('empty'):
        rows = entities.get('data', {})
        for row in rows:
            sku_id = str(row.get('id'))
            sku = Sku()
            sku['skuId'] = sku_id
            sku['batchNo'] = batch_no
            sku['supplierId'] = sp_id
            sku['supplierName'] = sp_name
            sku_list.append(sku)

    return sku_list


# 解析spu列表
def parse_spu(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    br_id = meta.get('brandId')
    br_name = meta.get('brandName')
    cat_id = meta.get('catalogId')
    cat_name = meta.get('catalogName')

    spu_list = list()
    rs = json.loads(response.text)
    if rs and rs.get('result', None):
        rows = rs.get('result', [])
        for row in rows:
            sku_id = str(row.get('spuId'))
            spec = row.get('specification')
            energy = row.get('energyDisabled')
            environ = row.get('environDisabled')
            tags = row.get('tags')
            spu = BackSpu()
            spu['spuId'] = sku_id
            spu['batchNo'] = batch_no
            spu['spec'] = spec
            spu['environ'] = energy
            spu['environ'] = environ
            spu['tags'] = tags
            spu['brandId'] = str(br_id)
            spu['brandName'] = br_name
            spu['catalog3Id'] = str(cat_id)
            spu['catalog3Name'] = cat_name
            spu_list.append(spu)

    return spu_list


# 解析spu列表
def parse_attr(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    cat_id = meta.get('catalogId')
    cat_name = meta.get('catalogName')

    rs = json.loads(response.text)
    if rs and rs.get('result', None):
        result = rs.get('result', {}).get('categoryAttributeWithProperties', [])
        cat_attr = BackCatAttr()
        cat_attr['catId'] = cat_id
        cat_attr['catName'] = cat_name
        cat_attr['attrs'] = result
        cat_attr['batchNo'] = batch_no
        return cat_attr

    return None


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    data = ItemData()
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')

    js = json.loads(response.text)
    if not js or 'result' not in js:
        logger.info('异常响应：[%s]' % sku_id)
        return None
    result = js.get('result', None)
    if not result:
        logger.info('[Item][%s]下架' % sku_id)
        return None
    item = result.get('item', {})
    skus = result.get('skus', [])
    sku = None
    if len(skus) == 1:
        sku = skus[0]
    else:
        for row in skus:
            if str(row.get('itemId')) == sku_id:
                sku = row
        if not sku:
            # 兼容异常数据
            sku = skus[0]

    if not sku:
        logger.info('sku解析异常：[%s]' % sku_id)
        return None
    if not item:
        logger.info('item解析异常：[%s]' % sku_id)
        return None

    # -------------------------------------------------
    data['batchNo'] = batch_no
    data['skuId'] = str(sku_id)
    spu_id = item.get('spuId', None)
    if not spu_id:
        spu_id = ''
    data['spuId'] = str(spu_id)
    data['skuName'] = item.get('name')
    data['skuImg'] = item.get('mainImage', '')
    data['soldCount'] = item.get('saleQuantity', 0)
    data['catalog3Id'] = str(item.get('categoryId'))

    full_price = sku.get('fullPrice')
    extra_price = sku.get('extraPrice')
    # 实际销售价格
    if 'price' in sku and sku.get('price', None):
        data['salePrice'] = parse_number(sku.get('price')) / 100
    else:
        if full_price:
            if 'channelPrice' in sku:
                data['salePrice'] = parse_number(full_price.get('channelPrice')) / 100
            elif 'agreementPrice' in sku:
                data['salePrice'] = parse_number(full_price.get('agreementPrice')) / 100
            else:
                data['salePrice'] = parse_number(extra_price.get('platformPrice')) / 100
        else:
            # 最大程度兼容
            data['salePrice'] = parse_number(extra_price.get('platformPrice')) / 100

    # 商品原价（商城原价、市场价格）
    if full_price:
        if 'platformPrice' in sku:
            data['originPrice'] = parse_number(full_price.get('platformPrice')) / 100
        else:
            data['originPrice'] = parse_number(full_price.get('marketPrice')) / 100
    else:
        data['originPrice'] = parse_number(extra_price.get('platformPrice')) / 100
    data['unit'] = '件'
    data['soldCount'] = parse_number(item.get('saleQuantity', 0))
    data['brandId'] = str(item.get('brandId'))
    data['brandName'] = item.get('brandName')
    data['supplierId'] = str(item.get('shopId'))
    sp_name = item.get('shopName')
    sp_sku_id = sku.get('skuCode', '')
    if sp_sku_id:
        sp_sku_id = sp_sku_id.strip()
    data['supplierName'] = sp_name
    data['supplierSkuId'] = sp_sku_id
    plat_code = None
    if '得力' in item.get('shopName'):
        plat_code = 'deli'
    sp_sku_code = convert_id2code(plat_code, sp_sku_id)
    data['supplierSkuCode'] = sp_sku_code
    data['supplierSkuLink'] = item.get('extra', {}).get('selfPlatformLink', '')
    data['brandModel'] = item.get('specification')
    on_shelf_at = item.get('onShelfAt')
    if on_shelf_at:
        data['onSaleTime'] = parse_timestamp(on_shelf_at)
    data['genTime'] = datetime.utcnow()
    # -------------------------------------------------

    return data


# 解析order列表
def parse_order_item(response):
    if not response.text:
        return None
    rs = json.loads(response.text)
    meta = response.meta
    sku_id = meta.get('skuId')
    supplier_id = meta.get('supplierId')
    supplier_name = meta.get('supplierName')

    orders = list()
    if rs:
        prev_order = None
        same_order_no = 1
        rows = rs.get('result', {}).get('orderItemDealRecordDtoPaging', {}).get('data', [])
        for idx, row in enumerate(rows):
            order = OrderItem()
            order['skuId'] = sku_id
            # 采购时间  1574840734000
            order_timestamp = row.get('dealDate')
            order_time = parse_timestamp(order_timestamp)
            # 采集截止
            if order_filter.to_save(order_time):
                order['count'] = row.get('dealCount')
                order['amount'] = row.get('dealTotalPrice') / 100
                order['orderDept'] = row.get('purchaseOrgName')
                order['deptId'] = md5(row.get('purchaseOrgName'))
                order['supplierId'] = supplier_id
                order['supplierName'] = supplier_name
                order['orderTime'] = order_time
                order['batchNo'] = time_to_batch_no(order_time)
                order['genTime'] = datetime.utcnow()

                if prev_order and prev_order.equals(order):
                    same_order_no = same_order_no + 1
                else:
                    same_order_no = 1
                addition = {
                    'sameOrderNo': same_order_no,
                    'orderTimeStr': order_timestamp,
                }
                sha1_id = build_sha1_order_id(order, addition)
                order['id'] = sha1_id
                order['orderId'] = sha1_id
                orders.append(order)
                prev_order = order

    return orders
